package cn.sdc.bugKiller.web;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import cn.sdc.bugKiller.bean.MemberBean;
import cn.sdc.bugKiller.bean.ProjectBean;
import cn.sdc.bugKiller.service.CodeDealService;
import cn.sdc.bugKiller.service.ContextService;
import cn.sdc.bugKiller.service.LoginService;

public class LogInOutServlet extends BasicServlet {

	private static CodeDealService codeService = new CodeDealService();    
	private static LoginService service = new LoginService();
	private static String METHOD_LOGIN = "in";
	private static String METHOD_LOGOUT = "out";
	
	public void exceute(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		
		Boolean isLoginOk = false;
		
		if(METHOD_LOGOUT.equals(methodName)){
			ContextService.clearSession();
		}else if(METHOD_LOGIN.equals(methodName) || methodName == null){
			ContextService.setSession(req.getSession());
			
			String username = req.getParameter("username");
			String password = req.getParameter("password");
			
			MemberBean member = service.getMemberByUsername(username);
			
			if(member == null){
			
				filedErrorMap.put("username", "E_LOGINOUT_001");
			}
//			else if(!password.equals(member.getPassword())){
//	
//				filedErrorMap.put("password", "E_LOGINOUT_002");
//			}
			else{
				ContextService.setCurrentUser(member);
				ProjectBean bean = codeService.getProjectById(member.getDefaultProject());
				ContextService.setCurrentProject(bean);
				isLoginOk = true;
			}
		}
		
		if(isLoginOk){
			resp.sendRedirect(req.getContextPath()+URI_HOME_SERVLET);
		}else{
			forward(req, resp, URI_LOGIN_JSP);
		}
	}
}
